#!/bin/sh

set -e
# for debugging
[ -n "$DEBUG" ] && set -x

IMGFILE=$PWD/disk.img


# we want everything except the final result to stderr
( exec 1>&2;

ESP_FILE=$PWD/boot.img



# get the systemd boot file name
ARCH=${TARGETARCH:-`uname -m`}
case $ARCH in
x86_64)
  BOOTFILE_SRC=/usr/lib/systemd/boot/efi/systemd-bootx64.efi
  BOOTFILE_DST=BOOTX64.EFI
  ;;
aarch64)
  BOOTFILE_SRC=/usr/lib/systemd/boot/efi/systemd-bootaa64.efi
  BOOTFILE_DST=BOOTAA64.EFI
  ;;
riscv64)
  BOOTFILE_SRC=/usr/lib/systemd/boot/efi/systemd-bootriscv64.efi
  BOOTFILE_DST=BOOTRISCV64.EFI
  ;;
esac

mkdir -p /tmp/efi
cd /tmp/efi

# input is a tarball on stdin with kernel and cmdline in /boot
# output is an iso on stdout

# extract. BSD tar auto recognises compression, unlike GNU tar
# only if stdin is a tty, if so need files volume mounted...
[ -t 0 ] || bsdtar xzf -

INITRD="$(find . -name '*.img')"
KERNEL="./kernel"
CMDLINE_FILE="$(find . -name cmdline)"
CMDLINE="$(cat $CMDLINE_FILE )"
UKI_FILE="linuxkit.efi"

# this is displayed as boot loader entry name
OS_RELEASE="NAME=\"LinuxKit\""

# PARTUUID for root
PARTUUID=$(cat /proc/sys/kernel/random/uuid)

cp $BOOTFILE_SRC $BOOTFILE_DST

cat >> loader/loader.conf <<EOF
timeout 0
EOF

ukify build --linux=$KERNEL \
            --initrd=$INITRD \
            --cmdline="$CMDLINE text" \
            --os-release=$OS_RELEASE \
            --output=$UKI_FILE

# FAT filesystem config
FAT_SIZE=32
SECTOR_SIZE=512
SECTORS_PER_CLUSTER=8
# these always include the Boot Sector and FS Information Sector (sector 0 and 1) among others for FAT32
RESERVED_SECTORS=32

# calculate sizes
UKI_FILE_SIZE=$(stat -c %s "$UKI_FILE")
EFI_FILE_SIZE=$(stat -c %s "$BOOTFILE_DST")
SYSTEMD_BOOT_FILE_SIZE=$(stat -c %s loader/loader.conf)

# this is the minimum size of our EFI System Partition
ESP_DATA_SIZE=$(( $UKI_FILE_SIZE + $EFI_FILE_SIZE + $SYSTEMD_BOOT_FILE_SIZE ))
ESP_DATA_SECTORS=$(( $ESP_DATA_SIZE / $SECTOR_SIZE ))

# File Allocation Table Sectors = (clusters + 2) * bytes per cluster / sector size
FILE_ALLOCATION_TABLE_SECTORS=$(( ( $ESP_DATA_SECTORS / $SECTORS_PER_CLUSTER + 2 ) * ( $FAT_SIZE / 8 ) / $SECTOR_SIZE ))

# there are two file allocation tables hence 2 * $FILE_ALLOCATION_TABLE_SECTORS
FAT_OVERHEAD_SECTORS=$(( $RESERVED_SECTORS + ( 2 * $FILE_ALLOCATION_TABLE_SECTORS ) ))
FAT_OVERHEAD_SIZE=$(( $FAT_OVERHEAD_SECTORS * $SECTOR_SIZE ))

# (x+1024)/1024*1024 rounds up to multiple of 1024KB, or 2048 sectors
# some firmwares get confused if the partitions are not aligned on 2048 blocks
# we will round up to the nearest multiple of 2048 blocks
# since each block is 512 bytes, we want the size to be a multiple of
# 2048 blocks * 512 bytes = 1048576 bytes = 1024KB
ESP_FILE_SIZE_KB=$(( ( ( ($ESP_DATA_SIZE + $FAT_OVERHEAD_SIZE + 1024 - 1) / 1024 ) + 1024 - 1) / 1024 * 1024 ))
# and for sectors
ESP_FILE_SIZE_SECTORS=$(( $ESP_FILE_SIZE_KB * 1024 / $SECTOR_SIZE ))

# create a raw disk with an EFI boot partition
# Stuff it into a FAT filesystem, making it as small as possible.
mkfs.vfat -v -F $FAT_SIZE -S $SECTOR_SIZE -s $SECTORS_PER_CLUSTER -R $RESERVED_SECTORS -C $ESP_FILE $(( $ESP_FILE_SIZE_KB )) > /dev/null
echo "mtools_skip_check=1" >> /etc/mtools.conf && \
mmd -i $ESP_FILE ::/EFI
mmd -i $ESP_FILE ::/EFI/BOOT
mmd -i $ESP_FILE ::/EFI/Linux
mmd -i $ESP_FILE ::/loader
mcopy -i $ESP_FILE $BOOTFILE_DST ::/EFI/BOOT/
mcopy -i $ESP_FILE $UKI_FILE ::/EFI/Linux/
mcopy -i $ESP_FILE loader/loader.conf ::/loader


# now make our actual filesystem image
# how big an image do we want?
# it should be the size of our ESP file+1MB for BIOS boot + 1MB for MBR + 1MB for GPT
ONEMB=$(( 1024 * 1024 ))
SIZE_IN_BYTES=$(( $(stat -c %s "$ESP_FILE") + 4*$ONEMB ))

# and make sure the ESP is bootable for BIOS mode
# settings
BLKSIZE=512
MB_BLOCKS=$(( $SIZE_IN_BYTES / $ONEMB ))

# make the image
dd if=/dev/zero of=$IMGFILE bs=1M count=$MB_BLOCKS

ESP_SECTOR_START=2048
ESP_SECTOR_END=$(( $ESP_SECTOR_START + $ESP_FILE_SIZE_SECTORS - 1 ))

# create the partitions - size of the ESP must match our image
# and make sure the ESP is bootable for BIOS mode
sgdisk --clear \
    --new 1:$ESP_SECTOR_START:$ESP_SECTOR_END --typecode=1:ef00 --change-name=1:'EFI System' --partition-guid=1:$PARTUUID \
    --attributes 1:set:2 \
     $IMGFILE

# copy in our EFI System Partition image
dd if=$ESP_FILE of=$IMGFILE bs=$BLKSIZE count=$ESP_FILE_SIZE_SECTORS conv=notrunc seek=$ESP_SECTOR_START

)

cat $IMGFILE
